package com.tianxiabuyi.utils;

import com.tianxiabuyi.model.pojo.HospitalUser;
import com.tianxiabuyi.persist.QBuilder;
import com.tianxiabuyi.persist.Where;

import java.util.*;

/**
 * 用户相关
 */
public final class UserUtil {

    /**
     * 获取userId所在科室列表
     * @param hospital
     * @param userId
     * @return
     */
    public static List<Map> getUserDept(Integer hospital, Integer userId) {
        List<Map> returnList = null;
        if (hospital == null || userId == null) {
            return returnList;
        }
        returnList = QBuilder.db("basedb").select("new map(hdu.deptId as dept_id, d.deptName as dept_name)").from("HospitalUser hu, Dept d, HospitalDeptUser hdu").where(new Where("hdu.hospital=", hospital).and("hdu.status=", ConstantUtil.STATUS_ENABLE).and("d.hospital=", hospital).and("d.status=", ConstantUtil.STATUS_ENABLE).and("hu.hospital=", hospital).and("hu.status=", ConstantUtil.STATUS_ENABLE).and("hdu.deptId=d.id").and("hdu.userId=hu.id").and("hu.id=", userId)).group("hdu.deptId, d.deptName order by hdu.deptId asc").query().getResultObj();
        return returnList;
    }

    /**
     * 获取userId所在自定义标签列表
     * @param hospital
     * @param userId
     * @return
     */
    public static List<Map> getUserCustomizeLabel(Integer hospital, Integer userId) {
        return getUserLabel(hospital, userId, ConstantUtil.CUSTOMIZE_HOSPITAL_LABEL);
    }

    /**
     * 获取userId所在标签列表
     * @param hospital
     * @param userId 1: 默认标签类, 2: 自定义标签类, 0或其他查全部
     * @param type
     * @return
     */
    public static List<Map> getUserLabel(Integer hospital, Integer userId, Integer type) {
        List<Map> returnList = new ArrayList<Map>();
        if (hospital == null || userId == null)
            return returnList;
        Where where = null;
        if (type != ConstantUtil.CUSTOMIZE_HOSPITAL_LABEL){
            where = new Where("hlm.hospital=", hospital).and("hlm.status=", ConstantUtil.STATUS_ENABLE).and("hl.hospital=", hospital).and("hl.status=", ConstantUtil.STATUS_ENABLE).and("hlm.labelId=hl.id").and("hl.category <> ", LabelUtil.ZERO).and("hlm.memberId=", userId).and("hlm.type=", ConstantUtil.HOSPITAL_LABEL_USER);
            returnList.addAll(QBuilder.db("basedb").select("new map(hlm.id as id, hlm.labelId as label_id, hl.name as label_name)").from("HospitalLabelMember hlm, HospitalLabel hl").where(where).group("hlm.labelId, hl.name order by hlm.labelId asc").query().getResultObj());
        }
        if (type != ConstantUtil.BASE_HOSPITAL_LABEL) {
            //查询所有科室
            List<Map> allDeptList = QBuilder.db("basedb").select("new map(id as dept_id, parent as parent, deptName as dept_name)").from("Dept").where(new Where("type=", ConstantUtil.DEPT_LINK).and("status=", ConstantUtil.STATUS_ENABLE).and("hospital=", hospital)).query().getResultObj();
            List<Map> userDeptList = getUserDept(hospital, userId);
            List<Map> parentList = new ArrayList<Map>();
            for (Map map:userDeptList) {
                getDeptPath(allDeptList, parentList, Tools.getDesc(map.get("dept_id"), ""));
            }
            StringBuilder builder = new StringBuilder("-1");
            for (Map map:parentList) {
                builder.append(",");
                builder.append(map.get("dept_id"));
            }
            where = new Where("hlm.hospital=", hospital).and("hlm.status=", ConstantUtil.STATUS_ENABLE).and("hl.hospital=", hospital).and("hl.status=", ConstantUtil.STATUS_ENABLE).and("hlm.labelId=hl.id").and("hl.category = ", LabelUtil.ZERO).and("(hlm.memberId=" + userId + " and hlm.type = 1) or (hlm.memberId in (" + builder.toString() + ") and hlm.type = 2)");
            returnList.addAll(QBuilder.db("basedb").select("new map(hlm.id as id, hlm.labelId as label_id, hl.name as label_name)").from("HospitalLabelMember hlm, HospitalLabel hl").where(where).group("hlm.labelId, hl.name order by hlm.labelId asc").query().getResultObj());
        }
        return returnList;
    }

    /**
     * 根据部门编号获取上级路径
     * @param deptList
     * @param deptId
     * @return
     */
    public static void getDeptPath(List<Map> deptList, List<Map> trueList, String deptId) {
        Iterator<Map> iterator = deptList.iterator();
        while (iterator.hasNext()) {
            Map deptMap = iterator.next();
            String id = deptMap.get("dept_id") + "";
            if (id.equals(deptId)) {//找到该条记录，根据父节点查询
                iterator.remove();
                trueList.add(deptMap);
                String parentId = deptMap.get("parent") + "";
                if (!"-1".equals(parentId)) {
                    getDeptPath(deptList, trueList, parentId);
                }
                break;
            }
        }
    }

    /**
     * 获取员工基础标签类名
     * @param hospital
     * @param userId
     * @param baseLabelCategoryName
     * @return
     */
    public static String getUserBaseLabelCategory(Integer hospital, Integer userId, String baseLabelCategoryName) {
        String name = "";
        if (hospital == null || userId == null || baseLabelCategoryName == null) {
            return name;
        }
        List<String> list = QBuilder.db("basedb").select("l.name").from("HospitalLabel l, HospitalLabelCategory lc, HospitalLabelMember lm").where(new Where("l.hospital=", hospital).and("l.status=", ConstantUtil.STATUS_ENABLE).and("l.id=lm.labelId").and("lm.type=", ConstantUtil.HOSPITAL_LABEL_USER).and("lm.memberId=", userId).and("lm.hospital=", hospital).and("lm.status=", ConstantUtil.STATUS_ENABLE).and("l.category=lc.id").and("lc.name=", baseLabelCategoryName).and("lc.status=", ConstantUtil.STATUS_ENABLE)).page(1, 1).query().getResultObj();
        if (list.size() > 0) {
            name = Tools.getDesc(list.get(0));
        }
        return name;
    }

    /**
     * 获取员工详细信息
     * @param hospital
     * @param userId
     * @return
     */
    public static Map getUserInfo(Integer hospital, Integer userId) {
        Map returnMap = null;
        if (hospital == null || userId == null) {
            return returnMap;
        }
        List<Map> userList = QBuilder.db("basedb").select("new map(hu.id as user_id, hu.name as name, hu.employeeId as employee_id, hu.phone as phone, hu.wechat as wechat, hu.qq as qq, hu.email as email, hu.gender as gender, hu.avatar as avatar, hu.entryTime as  entry_time, (case when hu.workStatus is null then 0 else hu.workStatus end) as work_status, (case when hu.lastLogin is null then 0 else 1 end) as open_status)").from("HospitalUser hu").where(new Where("hu.hospital=", hospital).and("hu.status=", ConstantUtil.STATUS_ENABLE).and("hu.id=", userId)).order("hu.id", "desc").page(1, 1).query().getResultObj();
        if (userList == null || userList.isEmpty()) {
            return returnMap;
        }
        returnMap = userList.get(0);
        returnMap.put("dept", getUserDept(hospital, userId));
        returnMap.put("label", getUserCustomizeLabel(hospital, userId));
        returnMap.put("title", getUserBaseLabelCategory(hospital, userId, ConstantUtil.HOSPITAL_BASE_TITLE_LABEL_CATEGORY));
        returnMap.put("position", getUserBaseLabelCategory(hospital, userId, ConstantUtil.HOSPITAL_BASE_POSITION_LABEL_CATEGORY));
        return returnMap;
    }

    /**
     * 根据userId获取HospitalUser对象
     * @param hospital
     * @param userId
     * @return
     */
    public static HospitalUser getUser(Integer hospital, Integer userId) {
        HospitalUser hospitalUser = null;
        if (hospital == null || userId == null) {
            return hospitalUser;
        }
        List<HospitalUser> hospitalUserList = QBuilder.db("basedb").select().from("HospitalUser hu").where(new Where("hu.hospital=", hospital).and("hu.status=", ConstantUtil.STATUS_ENABLE).and("hu.id=", userId)).page(1, 1).query().getResultObj();
        if (hospitalUserList != null && !hospitalUserList.isEmpty()) {
            hospitalUser = hospitalUserList.get(0);
        }
        return hospitalUser;
    }

    /**
     * 根据phone获取HospitalUser对象
     * @param phone
     * @return
     */
    public static HospitalUser getUser(String phone) {
        HospitalUser hospitalUser = null;
        phone = Tools.getDesc(phone, "");
        if (phone.isEmpty()) {
            return hospitalUser;
        }
        List<HospitalUser> hospitalUserList = QBuilder.db("basedb").select().from("HospitalUser hu").where(new Where("hu.status=", ConstantUtil.STATUS_ENABLE).and("hu.phone=", phone)).page(1, 1).query().getResultObj();
        if (hospitalUserList != null && !hospitalUserList.isEmpty()) {
            hospitalUser = hospitalUserList.get(0);
        }
        return hospitalUser;
    }

    /**
     * 根据科室id请求员工简要信息
     * @param hospital
     * @param deptId
     * @return
     */
    public static Map<String, List<Map>> getUserInDept(Integer hospital, Integer deptId) {
        Map<String, List<Map>> returnMap = new HashMap<String, List<Map>>();
        if (hospital == null) {
            return returnMap;
        }
        deptId = Tools.getInt(deptId, 0);
        Where where = new Where();
        if (deptId == 0) {
            where.and("d.parent=", "-1");
        } else {
            where.and("d.parent=", deptId);
            List<Map> userList = QBuilder.db("basedb").select("new map(hu.id as user_id, hu.employeeId as employee_id, hu.name as name, hu.phone as phone, hu.avatar as avatar, hu.hidden as is_hidden, hu.gender as gender)").from("Dept d, HospitalDeptUser hdu, HospitalUser hu").where(new Where("hdu.hospital=", hospital).and("hdu.status=", ConstantUtil.STATUS_ENABLE).and("d.hospital=", hospital).and("d.status=", ConstantUtil.STATUS_ENABLE).and("hu.hospital=", hospital).and("hu.status=", ConstantUtil.STATUS_ENABLE).and("hdu.deptId=d.id").and("hdu.userId=hu.id").and("hdu.deptId=", deptId)).order("hdu.id", "asc").query().getResultObj();
            if (userList != null && !userList.isEmpty()) {
                List<Integer> idList = QBuilder.db("basedb").select("hlc.id as id").from("HospitalLabelCategory hlc").where(new Where("hlc.hospital=0").and("hlc.status=", ConstantUtil.STATUS_ENABLE).and("hlc.name=", "职位")).order("hlc.id", "desc").limit(1).query().getResultObj();
                if (idList != null && !idList.isEmpty()) {
                    Integer LabelCategory = idList.get(0);
                    Map<Integer, List<String>> titleMap = LabelUtil.getTitle(hospital, LabelCategory, 0);
                    for (Map userMap : userList) {
                        Integer userId = Tools.getInt(userMap.get("user_id") + "", -11);
                        List<String> titleList = titleMap.get(userId);
                        userMap.put("title", LabelUtil.joint(titleList, " "));
                    }
                }
            }
            returnMap.put("user", userList);
        }
        List<Map> deptList = QBuilder.db("basedb").select("new map(d.id as dept_id, d.deptName as dept_name)").from("Dept d").where(where.and("d.hospital=", hospital).and("d.status=", ConstantUtil.STATUS_ENABLE).and("d.type=", ConstantUtil.DEPT_LINK)).query().getResultObj();
        if (deptList != null && !deptList.isEmpty()) {
            List<Map> countList = LabelUtil.getCountInDept(hospital, 0);
            if (countList == null) {
                countList = new ArrayList<Map>();
            }
            List<Map> subDeptList = LabelUtil.getSubDeptCount(hospital);
            if (subDeptList == null) {
                subDeptList = new ArrayList<Map>();
            }
            for (Map deptMap : deptList) {
                Integer _deptId = Tools.getInt(deptMap.get("dept_id") + "", -1);
                boolean userFlag = false;
                boolean deptFlag = false;
                for (Map subDeptMap : subDeptList) {
                    Integer _id = Tools.getInt(subDeptMap.get("id") + "", -11);
                    if (_id.equals(_deptId)) {
                        Integer count = Tools.getInt(subDeptMap.get("count") + "", 0);
                        if (count >= 1) {
                            deptMap.put("has_child_dept", 1);
                        } else {
                            deptMap.put("has_child_dept", 0);
                        }
                        deptFlag = true;
                        break;
                    }
                }
                for (Map countMap : countList) {
                    Integer _id = Tools.getInt(countMap.get("id") + "", -11);
                    if (_id.equals(_deptId)) {
                        Integer count = Tools.getInt(countMap.get("count") + "", 0);
                        if (count >= 1) {
                            deptMap.put("has_user", 1);
                        } else {
                            deptMap.put("has_user", 0);
                        }
                        userFlag = true;
                        break;
                    }
                }
                if (!userFlag) {
                    deptMap.put("has_user", 0);
                }
                if (!deptFlag) {
                    deptMap.put("has_child_dept", 0);
                }
            }

        }
        returnMap.put("dept", deptList);
        return returnMap;
    }


    /**
     *
     * @param hospital
     * @param keywords
     * @return
     */
    public static Map<String, List<Map>> getContact(Integer hospital, String keywords) {
        Map<String, List<Map>> returnMap = new HashMap<String, List<Map>>();
        if (hospital == null) {
            return returnMap;
        }
        keywords = Tools.getDesc(keywords, "").replace("/", "//").replace("\\", "/\\\\").replace("%", "/%").replace("_", "/_");

        // user
        List<Map> userList = QBuilder.db("basedb").select("new map(hu.id as user_id, hu.name as name, hu.phone as phone, hu.avatar as avatar, hu.hidden as is_hidden, hu.gender as gender)").from("HospitalUser hu").where(new Where("hu.hospital=", hospital).and("hu.status=", ConstantUtil.STATUS_ENABLE).and("name like '%" + keywords + "%' escape '/'")).query().getResultObj();
        returnMap.put("user", userList);

        // dept
        List<Map> deptList = QBuilder.db("basedb").select("new map(d.id as dept_id, d.deptName as dept_name)").from("Dept d").where(new Where("d.hospital=", hospital).and("d.status=", ConstantUtil.STATUS_ENABLE).and("d.type=", ConstantUtil.DEPT_LINK).and("d.deptName like '%" + keywords + "%' escape '/'")).query().getResultObj();
        returnMap.put("dept", deptList);

        // label
//        List<Map> labelList = QBuilder.db("basedb").select().from("HospitalLabelCategory hlc").where(new Where("hlc.hospital=", hospital).and("hlc.status=", ConstantUtil.STATUS_ENABLE).and("hlc.name like '%" + keywords + "%'")).query().getResultObj();
        List<Map> labelList = QBuilder.db("basedb").select().from("HospitalLabel hl").where(new Where("hl.hospital=", hospital).and("hl.status=", ConstantUtil.STATUS_ENABLE).and("hl.name like '%" + keywords + "%' escape '/'")).query().getResultObj();
        returnMap.put("label", labelList);

        return returnMap;
    }

}
